<template>
  <el-form ref="form" label-width="80px">
    <el-form-item>
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :headers="customHeaders"
        :on-success="handleProgress"
        :on-remove="handleRemove"
        :file-list="state.fileList"
        :before-upload="beforeAvatarUpload"
        list-type="picture">
        <el-button size="small" type="primary">点击上传</el-button>
        <template #tip>
          <div class="el-upload__tip">只能上传 jpg/png 文件</div>
        </template>
      </el-upload>
    </el-form-item>
  </el-form>
  <div class="add-dialog-submit">
    <el-button @click="onSubmit(0)">取消</el-button>
    <el-button type="primary" @click="onSubmit(1)">确认</el-button>
  </div>
</template>

<script setup>
  import { ref,reactive,onMounted,computed } from 'vue';
  import { ElMessage  } from 'element-plus';
  import { serverUrl ,uploadUrl} from '@/utils/const'
  import API from "@/utils/api";
  import { defineProps, defineEmits } from 'vue';
  const emits = defineEmits(['closeImgDialog']);
  const props = defineProps({
    parmas: Object,
  });
  computed(() => {
    return uploadUrl
  })
  const customHeaders = ref({
    'token-admin': localStorage.getItem('token'),
  });
  const state = reactive({
    fileList:[],
    fileListInfo:[],
  })
  const handleProgress = ((file, fileList) => {
    state.fileListInfo.push(file.data[0])
  })
  const handleRemove = ((file, fileList) => {
    const finalList = []
    fileList.forEach(item => {
      if(item.response) {
        finalList.push(item.response.data[0])
      }else {
        finalList.push(item.url)
      }
    });
    state.fileListInfo = finalList
  })
  function beforeAvatarUpload(file) {
    const isJPG = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/webp' || file.type === 'image/png'  || file.type === 'image/gif')
    if (!isJPG) {
      ElMessage.warning('上传轮播图片只能是 JPG/PNG 格式!')
    }
    return isJPG
  }
  const onSubmit = ((val) => {
    if(val === 0) {
      return emits('closeImgDialog',0);
    }else {
      if(state.fileListInfo.length < 1)  {
        return ElMessage.error('请上传图片哦！')
      }
      API.carouselsList.editCarousels({img_urls:state.fileListInfo}, res => {
        if(res.code === 0) {
          emits('closeImgDialog',1)
          ElMessage.success('提交成功')
        }
      })
    }
  })
  onMounted(() =>{
    if(props.parmas.length > 0) {
      props.parmas.forEach((item,index) => {
        state.fileList.push({
          name: '',
          url: item.img_url
        })
        state.fileListInfo.push(item.img_url)
      })
    }
  })
</script>

<style lang="scss" scoped>
.add-dialog-submit {
  margin-top: 30px;
}
</style>